package generating;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import common.CatAndPoints;
import common.QuestionDetails;
import common.QuestionManager;
import common.SQLCall;

/**
 * Create a new exam with random question.
 *
 */
public class Generate
{
	private Connection conn;

	public Generate(Connection c)
	{
		conn = c;
	}

	/**
	 * Go through the step to generate a preview exam
	 * 
	 * @param date_scheduled
	 *            The date the exam will be given
	 * @param author_id
	 *            The id of the author
	 */
	public int generate(String date_scheduled, int author_id)
	{
		QuestionManager qManager;
		CatAndPoints qCategory;
		try
		{
			qManager = SQLCall.getQuestionManager(conn).reset();
			qCategory = SQLCall.getCategoryList(conn);
		} catch (SQLException e1)
		{
			e1.printStackTrace();
			return -2;
		}

		ArrayList<Integer> examQuestion = new ArrayList<Integer>();

		int examID = -1;

		for (int cat : qCategory)
		{
			int remainPoints = qCategory.getPoints(cat);

			while (remainPoints > 0)
			{
				QuestionDetails qd = qManager.getQuestion(cat, remainPoints);
				examQuestion.add(qd.getID());
				remainPoints -= qd.getPoints();
			}
		}
		// Insert exam question into database
		try
		{
			java.sql.Date date;
			SimpleDateFormat df = new SimpleDateFormat("M/d/yyyy");
			date = new java.sql.Date(df.parse(date_scheduled).getTime());
			
			examID = SQLCall.getNextSeq(conn, "exam_s1");

			// Create entry in EXAM table
			PreparedStatement insertExam = conn.prepareStatement(
					"INSERT INTO EXAM (exam_id, date_created, date_scheduled, " +
					"author_id) VALUES(?, SYSDATE, ?, ?)");

			insertExam.setInt(1, examID);
			insertExam.setDate(2, date);
			insertExam.setInt(3, author_id);
			insertExam.executeQuery();

			insertExam.close();

			// Insert question_id into EXAM_QUESTION
			PreparedStatement uploadStmt = conn.prepareStatement(
					"INSERT INTO EXAM_QUESTION " +
					"(exam_id, question_id, q_version) VALUES(?,?,0)");
			uploadStmt.setInt(1, examID);
			for (int i = 0; i < examQuestion.size(); i++)
			{
				uploadStmt.setInt(2, (Integer) examQuestion.get(i));
				uploadStmt.execute();
			}
			uploadStmt.close();
		} catch (SQLException sqlError)
		{
			sqlError.printStackTrace();
		} catch (ParseException e)
		{
			System.out.println("Incorrectly Formatted Date");
		}
		
		SQLCall.clear();

		return examID;
	}

}
